#pragma once

#include <Arduino.h>
#include <vector>

extern void button_handle(void);

template<size_t NUMS>
class Buttons
{
public:
    using self = Buttons;
public:
    Buttons()
        : _button_pins(NUMS, 0)
        , _button_map(NUMS, false)
    {}

    void init(const std::vector<int>& pins)
    {
        for (int i = 0; i < end(); ++i)
        {
            _button_pins[i] = pins[i];
            pinMode(_button_pins[i], INPUT_PULLUP);
            attachInterrupt(digitalPinToInterrupt(_button_pins[i]), button_handle, FALLING);
        }
    }

    int end()
    {
        return NUMS;
    }

    int get_value()
    {
        for (int i = 0; i < end(); ++i)
        {
            if (_button_map[i])
            {
                erase_flag(i);
                return i;
            }
        }
        return end();
    }

    void waiting()
    {
        while (get_value() == end());
    }
private:
    void erase_flag(int index)
    {
        _button_map[index] = false;
    }
public:
    std::vector<int> _button_pins;
    std::vector<char> _button_map;
};